#include "CUdpNetwork.h"

CUdpNetwork* CUdpNetwork::singleton = 0;

CUdpNetwork::CUdpNetwork()
{
    this->udp_socket = new QUdpSocket;
}

CUdpNetwork::~CUdpNetwork()
{
    delete udp_socket;
}

CUdpNetwork* CUdpNetwork::get_instance()
{
    if(!singleton)
    {
        singleton = new CUdpNetwork;
    }

    return singleton;
}

void CUdpNetwork::listen(quint16 port)
{
    // Initialise une connexion UDP
    CUdpNetwork::get_instance()->udp_socket->bind(port, QUdpSocket::DontShareAddress);

    // Attend que des paquets arrivent
    QObject::connect(CUdpNetwork::get_instance()->udp_socket, SIGNAL(readyRead()),this, SLOT(select_action()));

    emit listening();
}

bool CUdpNetwork::is_listening()
{
    return CUdpNetwork::get_instance()->udp_socket->ListeningState > 3;
}

void CUdpNetwork::select_action()
{
    QUdpSocket *socket = qobject_cast<QUdpSocket *>(sender());
    QString action = CUdpNetwork::get_instance()->receive();

    if(action == "login")
    {
        emit login(socket);
    }
    else if(action == "move")
    {
        emit move(socket);
    }
}

QString CUdpNetwork::receive()
{
    QByteArray datagram;
    QHostAddress sender;
    quint16 senderPort;
    while (CUdpNetwork::get_instance()->udp_socket->hasPendingDatagrams())
    {
        datagram.resize(CUdpNetwork::get_instance()->udp_socket->pendingDatagramSize());

        CUdpNetwork::get_instance()->udp_socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        //emit is_receiving(QString::fromAscii(datagram.data()));

        return QString::fromAscii(datagram.data());
    }
}

QString CUdpNetwork::receive(QUdpSocket* socket)
{
    QByteArray datagram;
    QHostAddress sender;
    quint16 senderPort;
    while (socket->hasPendingDatagrams())
    {
        datagram.resize(socket->pendingDatagramSize());

        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        //emit is_receiving(QString::fromAscii(datagram.data()));

        return QString::fromAscii(datagram.data());
    }
}


void CUdpNetwork::send(QString message)
{
    QByteArray datagram = message.toLocal8Bit();
    QHostAddress sender;
    quint16 senderPort;
    CUdpNetwork::get_instance()->udp_socket->writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
}

void CUdpNetwork::send(QUdpSocket* socket, QString message)
{
    QByteArray datagram = message.toLocal8Bit();
    QHostAddress sender;
    quint16 senderPort;
    socket->writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
}
